package han.parser;

import han.entity.FriendMessageEntity;
import han.entity.GroupMessageEntity;
import han.entity.MessageEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author: Han
 * @date: 2018/7/11 16:17
 * @dscription: 消息解析器
 */
public class MessageParser {

    public final static String GROUP_MESSAGE = "group_message";
    private final static String FRIEND_MESSAGE = "message";

    public static MessageEntity message(String rowStr) {

        JSONObject rowJsonObj = new JSONObject(rowStr);
        JSONObject anonymJsonObj = rowJsonObj.getJSONArray("result").getJSONObject(0);
        String type = anonymJsonObj.getString("poll_type");
        JSONObject valueJsonObj = anonymJsonObj.getJSONObject("value");
        if (GROUP_MESSAGE.equals(type)) {
            return groupMessage(valueJsonObj);
        } else if (FRIEND_MESSAGE.equals(type)) {
            return friendMessage(valueJsonObj);
        } else {
            return null;
        }
    }

    /**
     * 解析好友消息实体
     *
     * @param valueJsonObj 消息内容
     * @return 好友消息
     */
    private static FriendMessageEntity friendMessage(JSONObject valueJsonObj) {
        JSONArray content = valueJsonObj.getJSONArray("content");
        String msg = content.getString(1);
        long fromUin = valueJsonObj.getLong("from_uin");
        long msgType = valueJsonObj.getLong("msg_type");
        long time = valueJsonObj.getLong("time");
        long toUin = valueJsonObj.getLong("to_uin");

        return new FriendMessageEntity(FRIEND_MESSAGE, msg, fromUin, toUin, msgType, time);
    }

    /**
     * 解析群组消息实体
     *
     * @param valueJsonObj 消息内容
     * @return 群组消息
     */
    private static GroupMessageEntity groupMessage(JSONObject valueJsonObj) {
        JSONArray content = valueJsonObj.getJSONArray("content");
        String msg = "";
        try {
            msg = content.getString(1);
        } catch (JSONException ignore) {
        }
        long fromUin = valueJsonObj.getLong("from_uin");
        long groupCode = valueJsonObj.getLong("group_code");
        long msgType = valueJsonObj.getLong("msg_type");
        long sendUin = valueJsonObj.getLong("send_uin");
        long toUin = valueJsonObj.getLong("to_uin");
        long time = valueJsonObj.getLong("time");

        return new GroupMessageEntity(GROUP_MESSAGE, msg, fromUin, toUin, sendUin, groupCode, msgType, time);
    }
}
